package com.jbit.examSystem.controller;

import com.github.pagehelper.PageHelper;
import com.jbit.examSystem.param.PageParam;
import com.jbit.examSystem.param.RankingParam;
import com.jbit.examSystem.pojo.Score;
import com.jbit.examSystem.pojo.TableDataInfo;
import com.jbit.examSystem.service.ScoreService;
import com.jbit.examSystem.vo.RankingVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;


@Controller
@RequestMapping("ranking")
public class RankingController {
    @Autowired
    private ScoreService scoreService;

    @RequestMapping("list")
    @ResponseBody
    public TableDataInfo list(PageParam page, Integer stuNo, RankingParam param){
        TableDataInfo respData = new TableDataInfo();
        if (param.getRankingByClass() == null || param.getRankingByTime() == null){
            param.setRankingByClass("10000");
            param.setRankingByTime("thisWeek");
        }
        try {
            PageHelper.startPage(page.getPageNum(), page.getPageSize(), true, true, false);
            List<Score> scores = scoreService.getAllScores(param);

            List<RankingVo> rankingVoList = convert2RankingVo(scores);

            respData.succeed(rankingVoList, 0);
        } catch (Exception e){
            respData.setCode(500);
            e.printStackTrace();
        }
        return respData;
    }

    private List<RankingVo> convert2RankingVo(List<Score> scores) {
        List<RankingVo> rankingVoList = new ArrayList<>();
        int i = 1;
        for (Score score : scores) {
            String accuracy = RankingVo.getAccuracy(score.getCorrectAmount(), score.getTestPaper().getAmount());
            RankingVo rankingVo = new RankingVo();
            rankingVo.setAccuracy(accuracy);
            rankingVo.setAmount(score.getTestPaper().getAmount());
            rankingVo.setCorrectAmount(score.getCorrectAmount());
            rankingVo.setOkAmount(score.getOkAmount());
            rankingVo.setRankingId(i);i++;
            rankingVo.setStuName(score.getStudent().getName());
            rankingVoList.add(rankingVo);
        }

        return rankingVoList;
    }
}
